from django.shortcuts import render
from django import http
from django.http import JsonResponse
from django.views import View
from apps.users.models import User
import json, re
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate, logout
from meiduo_mall.utils.views import LoginRequiredMixin



# Create your views here.

# 用户名检测
class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        '''判断用户名是否重复'''
        # 1.查询username在数据库中的个数
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '访问数据库失败'})

        # 2.返回结果(json) ---> code & errmsg & count
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'count': count})


# 电话检测
class MobileCountView(View):

    def get(self, request, mobile):
        '''判断手机号是否重复注册'''
        # 1.查询mobile在mysql中的个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '查询数据库出错'})

        # 2.返回结果(json)
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'count': count})


# 注册
class RegisterView(View):

    def post(self, request):
        '''注册功能接口'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        allow = dict.get('allow')
        sms_code_client = dict.get('sms_code')

        # 2.校验参数(整体)
        if not all([username, password, password2, mobile, allow, sms_code_client]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        # 3.单个检验: username
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 400,
                                 'errmsg': 'username格式不正确'})

        # 4.password
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'errmsg': 'password格式不正确'})

        # 5.password 和 password2
        if password != password2:
            return JsonResponse({'code': 400,
                                 'errmsg': '两次输入密码不一致'})

        # 6.mobile
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': 'mobile格式不正确'})

        # 7.allow
        if allow != True:
            return JsonResponse({'code': 400,
                                 'errmsg': '请勾选协议'})

        # 8.链接redis, 获取链接对象
        redis_conn = get_redis_connection('verify_code')

        # 9.利用练级对象, 获取服务端的短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 10.判断服务端的短信验证码是否存在
        if not sms_code_server:
            return JsonResponse({'code': 400,
                                 'errmsg': '短信验证码过期'})

        # 11.对比前后端的短信验证码
        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 400,
                                 'errmsg': '输入的短信验证码有误'})

        # 12.把username, password mobile保存到User
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '保存到数据库出错'})

        # 状态保持:
        login(request, user)

        # 13.返回结果(json)
        # return JsonResponse({'code': 0,
        #                      'errmsg': 'ok'})

        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})

        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # 补充内容:购物车的合并
        # response = merge_cart_cookie_to_redis(request, response)

        return response


# 登录
class LoginView(View):
    def post(self, request):
        dict = json.loads(request.body.decode())
        account = dict.get('username')
        password = dict.get('password')
        remembered = dict.get('remembered')

        # 2.校验(整体 + 单个)
        if not all([account, password]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        # 2.5 多账号登陆 判断是为手机号还是用户
        if re.match('^1[3-9]\d{9}$', account):  # 手机号判断
            User.USERNAME_FIELD = 'mobile'
        else:
            print('account为用户名类型')
            pass

        # 3.验证是否能够登录
        user = authenticate(username=account,
                            password=password)

        if user is None:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '用户名或密码错误'})

        login(request, user)

        if remembered != True:
            # 7.如果没有记住: 关闭立刻失效
            request.session.set_expiry(0)
        else:
            # 6.如果记住:  设置为两周有效
            request.session.set_expiry(None)

        response = http.JsonResponse({'code': 0,
                                  'errmsg': 'ok'})
        # 设置cookie
        response.set_cookie('username',user.username)

            # 8.返回json
        return response


# 退出登录 接口delete，删除数据
class LogoutView(View):
    def delete(self, request):
        logout(request)
        response = http.JsonResponse({'code': 0,
                                      'errmsg': 'ok'})

        response.delete_cookie('username')

        return response


class UserInfoView(LoginRequiredMixin,View):
    """用户中心"""

    def get(self, request):

            # 如果登录, 则正常返回该页面数据
            data_dict = {
                'code': 0,
                'errmsg': 'ok',
                'info_data': {
                    'username': '',
                    'mobile': '',
                    'email': '',
                    'email_active': '',

                }
            }
            return http.JsonResponse(data_dict)


